package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.guli.service.oss.service.FileService;
import com.atguigu.guli.service.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @desc 文件操作实现
 * @auther Administrator
 * @create 2020/5/19
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OssProperties ossProperties;

    /**
     * 阿里云文件上传
     *
     * @param inputStream      输入流
     * @param module           文件夹名称
     * @param originalFileName 原始文件名
     * @return 文件在oss服务器上的url路径
     */
    @Override
    public String upload(InputStream inputStream, String module, String originalFileName) {

        // 获取oss配置信息
        String endpoint = ossProperties.getEndpoint();
        String keyid = ossProperties.getKeyid();
        String keysecret = ossProperties.getKeysecret();
        String bucketname = ossProperties.getBucketname();

        //判断oss实例是否存在：如果不存在则创建，如果存在则获取

        // 1、创建oss客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);
        // 判断是否存在
        if(!ossClient.doesBucketExist(bucketname)){
            ossClient.createBucket(bucketname);
            // 设置权限，公共读权限
            ossClient.setBucketAcl(bucketname, CannedAccessControlList.PublicRead);
        }
        //2、构建objectName: 文件路径，文件存储策略
        String folder = new DateTime().toString("yyyyMMdd");
        // 3、文件名
        String fileName = UUID.randomUUID().toString();
        // 4、获取文件拓展名
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 5、文件上传路径
        String key = module + "/" + folder + "/" + fileName + fileExtension;
        // 6、上传文件
        ossClient.putObject(bucketname, key, inputStream);

        // 7、关闭ossClient
        ossClient.shutdown();

        // 返回oss上的文件url
        return "https://" + bucketname + "." + endpoint + "/" + key;
    }

    @Override
    public void removeFile(String url) {
        // 获取oss配置信息
        String endpoint = ossProperties.getEndpoint();
        String keyid = ossProperties.getKeyid();
        String keysecret = ossProperties.getKeysecret();
        String bucketname = ossProperties.getBucketname();

        // 1、创建oss客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);

        String host = "https://" + bucketname + "." + endpoint + "/";

        // 获取objectName
        String objectName = url.substring(host.length());

        // 2、删除文件
        ossClient.deleteObject(bucketname, objectName);
        // 关闭ossClient
        ossClient.shutdown();
    }
}
